package com.example.demo1.service.impl;

import com.example.demo1.pojo.po.User;
import com.example.demo1.service.TokenService;
import com.example.demo1.util.MD5;
import com.example.demo1.util.RedisAPI;
import com.example.demo1.util.UserAgentUtil;
import cz.mallat.uasparser.UserAgentInfo;
import javafx.scene.input.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Description: 本类用于
 * Created by 白相宇 on 2019/12/26 9:38
 */
@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private RedisAPI redisAPI;
    /**
     * 生成token : 客户端信息+ 邮箱的md5（32位）+ 用户id + 当前时间年月日时分秒 + agent的6位码
     * @param agent
     * @param user
     * @return
     */
    @Override
    public String generationToken(String agent, User user) {

        agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36";
        try {
            UserAgentInfo userAgentInfo= UserAgentUtil.getUasParser().parse(agent);
            String userAgentInfoDeviceType=userAgentInfo.getDeviceType();
            StringBuffer sb=new StringBuffer();
            sb.append("token: ");
            if (UserAgentInfo.UNKNOWN.equals(userAgentInfoDeviceType)){
                if (UserAgentUtil.CheckAgent(agent)){
                    sb.append("MOBILE- ");
                }else{
                    sb.append("PC- ");
                }
            }
            sb.append(MD5.getMd5(user.getUserCode(),32));
            sb.append(user.getId());
            sb.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            sb.append(MD5.getMd5(agent,6));
            /**
             * 将token存入redis
             */
            RedisAPI redisAPI=new RedisAPI();
            JedisPool jedisPool=redisAPI.createJedisPool();
            Jedis jedis=jedisPool.getResource();
            jedis.set("Token",sb.toString());

            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存到缓存
     * @param key : 键
     * @param value : 值
     */
    @Override
    public void saveToken(String key,String value){
        redisAPI.set(key,value);
    }



    public static void main(String[] args) {
        TokenServiceImpl tokenService=new TokenServiceImpl();
        User user=new User();
        user.setUserCode("123456@qq.com");
        user.setId(5);
        System.out.println(tokenService.generationToken("",user));
    }

}
